'use strict';

const Controller = require('egg').Controller;

class KnowledgeController extends Controller {
    async delete() {
        // 删除某一条知识库
        try {
            const { phone, id } = this.ctx.request.body
            const result = await this.service.knowledge.delete({
                phone,id
            })
            if(result.code === 1) {
                this.ctx.response.body = {
                    code: 1,
                    msg: result.msg
                }
            } else {
                this.ctx.response.body = {
                    code: 0,
                    msg: result.msg
                }
            }
        } catch(e) {
            this.ctx.response.body = {
                code: 0,
                msg: e.message
            }
        }
        
    }
    async list() { // 获取所有的知识库数据
        try {
            const { phone } = this.ctx.request.body
            const result = await this.service.knowledge.list(phone)
            this.ctx.response.body = {
                code: 1,
                data: result.data
            }
        } catch(e) {
            this.ctx.response.body = {
                code: 0,
                data: e.message
            }
        }
        
    }
  async add() {
    try {
      // 添加知识库
        const { type, name, detail } = this.ctx.request.body
        const token = this.ctx.cookies.get('token')
        let phone = ''
        this.app.jwt.verify(token, this.app.config.jwt.secret, (err, decoded) => {
            console.log(err, decoded)
        if (err) { // token未提供，token过期
            throw err
        } else {
            phone = decoded.phone
        }
        })
        const addResult = await this.service.knowledge.add({
            phone,
            type,
            name,
            detail
        })
        if (addResult.code === 1) {
            this.ctx.response.body = {
                code: 1,
                id: addResult.id,
                msg: '添加成功'
            }
        } else {
            this.ctx.response.body = {
                code: 0,
                msg: '添加失败'
            }
        }
    } catch(e) {
        this.ctx.response.body = {
            code: 0,
            msg: e.message
        }
    }
  }
}

module.exports = KnowledgeController;
